/**
 * Copyright (C) 2016 Hyphenate Inc. All rights reserved.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.srwl.mytx.activity;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.google.android.material.snackbar.Snackbar;
import com.huantansheng.easyphotos.utils.Color.ColorUtils;
import com.huantansheng.easyphotos.utils.system.SystemUtils;
import com.srwl.mytx.Constant;
import com.srwl.mytx.MyApplication;
import com.srwl.mytx.R;


public class BaseActivity extends AppCompatActivity {

    protected boolean pause = false;
    protected int screenHeight;
    protected int screenWidth;
    private ProgressDialog progressDialog;
    protected InputMethodManager inputMethodManager;
    private LocalBroadcastManager broadcastManager;
    private BroadcastReceiver broadcastReceiver;

    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setStatusDark();
        if (!isTaskRoot()) {
            Intent intent = getIntent();
            String action = intent.getAction();
            if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) && action.equals(Intent.ACTION_MAIN)) {
                finish();
                return;
            }
        }
        MyApplication.getInstance().saveActivity(this);
        inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        screenHeight = getResources().getDisplayMetrics().heightPixels;
        screenWidth = getResources().getDisplayMetrics().widthPixels;
        initBroadcast();
    }


    protected void setStatusDark() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int statusColor = getWindow().getStatusBarColor();
            if (statusColor == Color.TRANSPARENT) {
                statusColor = ContextCompat.getColor(this, R.color.colorPrimaryDark);
            }
            if (ColorUtils.isWhiteColor(statusColor)) {
                SystemUtils.getInstance().setStatusDark(this, true);
            }
        }
    }

    /**
     * 设置为全屏，且状态栏为透明背景，
     * 字体显示为深色（6.0及以上）
     */
    protected void setupStartBar() {
        Window window = getWindow();
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);//  全屏，状态栏字体黑色
        } else {
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        }
        window.setStatusBarColor(getResources().getColor(R.color.transparent));
    }


    @Override
    protected void onPause() {
        super.onPause();
        pause = true;
        // MobclickAgent.onPause(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        // umeng
        // MobclickAgent.onResume(this);
        pause = false;
    }

    @Override
    protected void onStart() {
        super.onStart();
        // umeng
        // MobclickAgent.onPause(this);
        //增加活动的activity 数量
        MyApplication.getInstance().onActivityStart();

    }

    @Override
    protected void onStop() {
        super.onStop();
        //减少活动的activity 数量
        MyApplication.getInstance().onActivityStop();
    }

    protected void showToast(final String toastContent) {
        showToast(getWindow().getDecorView(), toastContent);
    }

    protected void showToast(final View view, final String toastContent) {
        runOnUiThread(new Runnable() {
            public void run() {
                // Toast.makeText(BaseActivity.this, toastContent, Toast.LENGTH_SHORT).show();
                // Snackbar.make(getWindow().getDecorView(), toastContent, Snackbar.LENGTH_LONG).show(); //这样虽然方便了，不用传view 参数进来，弊端：当键盘打开的时候，键盘会遮住Snackbar;
                Snackbar.make(view, toastContent, Snackbar.LENGTH_LONG).show();
            }
        });
    }

    public void showToast_v1(final String toastContent) {
        Toast.makeText(BaseActivity.this, toastContent, Toast.LENGTH_SHORT).show();
    }

    protected void showProgressDialog(String message) {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(BaseActivity.this);
        }
        progressDialog.setMessage(message);
        if (!progressDialog.isShowing()) {
            progressDialog.show();
        }
    }

    protected void hideProgressDialog() {

        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }

    protected void hideSoftKeyboard() {
        if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null)
                inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    private void initBroadcast() {
        broadcastManager = LocalBroadcastManager.getInstance(this);

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constant.ACTION_LOGIN_USER_INFO_CHANGE);
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                onAccountChange();
            }
        };
        broadcastManager.registerReceiver(broadcastReceiver, intentFilter);
    }

    /**
     * 当登录账户改变，一般是从游客身份登录或者注册后，会被调用
     */
    protected void onAccountChange() {

    }

    /**
     * back
     *
     * @param view
     */
    public void back(View view) {
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MyApplication.getInstance().removeActivity(this);
        inputMethodManager = null;
        if (broadcastManager != null) {
            broadcastManager.unregisterReceiver(broadcastReceiver);
        }
    }
}
